package com.spice.im;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.SDKInitializer;
//import com.lidroid.xutils.bitmap.factory.BitmapFactory;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.stb.isharemessage.BeemApplication;
//import com.stb.isharemessage.ui.feed.OtherFeedListActivity.MyLocationListener;




import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
//import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.util.Log;

public class SpiceApplication extends Application{
	public static final String ZHIDING_ACCOUNT_USERNAME_KEY = "zhiding_account_username_key";
    /** Preference key for display offline contact. */
    public static final String SHOW_OFFLINE_CONTACTS_KEY = "show_offline_contacts";
    /** Preference key for auto away message. */
    public static final String AUTO_AWAY_MSG_KEY = "auto_away_msg";
    /** Preference key for compact chat ui. */
    public static final String USE_COMPACT_CHAT_UI_KEY = "use_compact_chat_ui";
    private SharedPreferences mSettings;
    private final PreferenceListener mPreferenceListener = new PreferenceListener();
    private boolean mIsAccountConfigured;
    private static SpiceApplication instance = null;
    //表情相关start
	public static List<String> mEmoticons = new ArrayList<String>();
	public static Map<String, Integer> mEmoticonsId = new HashMap<String, Integer>();
	public static List<String> mEmoticons_Zem = new ArrayList<String>();
	public static List<String> mEmoticons_Zemoji = new ArrayList<String>();
    //表情相关end
	
    //百度定位start
	public LocationClient mLocationClient;
	public LocationClientOption option;
//	public GeofenceClient mGeofenceClient;
	public MyLocationListener mMyLocationListener;
	public double mLongitude;
	public double mLatitude;
	public String mGpsAddr;
    //百度定位end
	
    public static SpiceApplication getInstance() {
    	if(instance == null){
    		Log.e("※※※※※※20131206※※※※※※", "※※※※※※※BeemApplication is null getInstance");
    		instance = new SpiceApplication();
    	}
        return instance;
    }
    /**
     * Constructor.
     */
    public SpiceApplication() {
    	
    }
    //启动程序调用此方法
    @Override
    public void onCreate() {
		super.onCreate();
		// 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
		SDKInitializer.initialize(this);
//        CrashHandler handler = CrashHandler.getInstance();
//        handler.init(getApplicationContext()); //在Appliction里面设置我们的异常处理器为UncaughtExceptionHandler处理器
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(this));
		for (int i = 1; i < 64; i++) {
			String emoticonsName = "[zem" + i + "]";
			int emoticonsId = getResources().getIdentifier("zem" + i,
					"drawable", getPackageName());
			mEmoticons.add(emoticonsName);
			mEmoticons_Zem.add(emoticonsName);
			mEmoticonsId.put(emoticonsName, emoticonsId);
		}
		for (int i = 1; i < 59; i++) {
			String emoticonsName = "[zemoji" + i + "]";
			int emoticonsId = getResources().getIdentifier("zemoji_e" + i,
					"drawable", getPackageName());
			mEmoticons.add(emoticonsName);
			mEmoticons_Zemoji.add(emoticonsName);
			mEmoticonsId.put(emoticonsName, emoticonsId);
		}
		
		mSettings = PreferenceManager.getDefaultSharedPreferences(this);
		String login = mSettings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		String password = mSettings.getString(BeemApplication.ACCOUNT_PASSWORD_KEY, "");
		mIsAccountConfigured = !("".equals(login) || "".equals(password));
		mSettings.registerOnSharedPreferenceChangeListener(mPreferenceListener);
		
		initImageLoader(getApplicationContext()); 
		
		// 获取当前用户位置
		mLocationClient = new LocationClient(this.getApplicationContext());
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
//		mGeofenceClient = new GeofenceClient(getApplicationContext());
		InitLocation();
		mLocationClient.start();
		if (mLocationClient != null && mLocationClient.isStarted())
		mLocationClient.requestOfflineLocation();
		System.out.println("开始获取");
    }
    //退出程序调用此方法
    //当终止应用程序对象时调用，不保证一定被调用，当程序是被内核终止以便为其他应用程序释放资源，那
    //么将不会提醒，并且不调用应用程序的对象的onTerminate方法而直接终止进   程
    @Override
    public void onTerminate() {
		super.onTerminate();
		mSettings.unregisterOnSharedPreferenceChangeListener(mPreferenceListener);
    }
    
    private List<Activity> list = new ArrayList<Activity>();
	public void addActivity(Activity activity) {
	    list.add(activity);
	}
    public void exit() {
        for (Activity activity : list) {
//        	if(activity instanceof ContactListPullRefListActivity){
////        		((ContactListPullRefListActivity)activity).onDestroyNew();
//        		((ContactListPullRefListActivity) activity).finishNew();
//        	}else if(activity instanceof BulkMsgContactListPullRefListActivity){
//        		((BulkMsgContactListPullRefListActivity) activity).finishNew();
        	 if(activity instanceof ContactFrameActivity){
        		((ContactFrameActivity) activity).finishNew();
        	}else
        		activity.finish();
        }
//        exitProgrames();
//        if(mEmoticons!=null){
//        	mEmoticons.clear();
//        	mEmoticons = null;
//        }
//        if(mEmoticonsId!=null){
//        	mEmoticonsId.clear();
//        	mEmoticonsId = null;	
//        }
//        if(mEmoticons_Zem!=null){
//        	mEmoticons_Zem.clear();
//        	mEmoticons_Zem = null;
//        }
//        if(mEmoticons_Zemoji!=null){
//        	mEmoticons_Zemoji.clear();
//        	mEmoticons_Zemoji = null;
//        }
        // 杀死该应用进程
//        android.os.Process.killProcess(android.os.Process.myPid());
//    	Object obj = null;
//    	for(int i=0;i<list.size();i++){
//    		obj = list.get(i);
//    		if(obj instanceof Activity)
//    			((Activity)obj).finish();
//    		else if(obj instanceof FragmentActivity)
//    			((FragmentActivity)obj).finish();
//    	}
//        System.exit(0);
    }
    /**
     * Tell if a XMPP account is configured.
     * @return false if there is no account configured.
     */
    //登录帐号是否已设置
    public boolean isAccountConfigured() {
    	return mIsAccountConfigured;
    }
    
    //配置信息修改侦听类
    /**
     * A listener for all the change in the preference file. It is used to maintain the global state of the application.
     */
    private class PreferenceListener implements SharedPreferences.OnSharedPreferenceChangeListener {

		/**
		 * Constructor.
		 */
		public PreferenceListener() {
		}
	
		@Override
		public void onSharedPreferenceChanged(SharedPreferences  sharedPreferences, String key) {
		    if (BeemApplication.ACCOUNT_USERNAME_KEY.equals(key) || BeemApplication.ACCOUNT_PASSWORD_KEY.equals(key)) {
			String login = mSettings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
			String password = mSettings.getString(BeemApplication.ACCOUNT_PASSWORD_KEY, "");
			mIsAccountConfigured = !("".equals(login) || "".equals(password));
		    }
		}
    }
    
    public void initImageLoader(Context context) {
//		// This configuration tuning is custom. You can tune every option, you may tune some of them,
//		// or you can create default configuration by
//		//  ImageLoaderConfiguration.createDefault(this);
//		// method.
//		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
//				.threadPriority(Thread.NORM_PRIORITY - 2)
//				.denyCacheImageMultipleSizesInMemory()
//				.memoryCache(new WeakMemoryCache()) //配置图片的内存缓存为memoryCache(new WeakMemoryCache()) 或者不使用内存缓存
//				.threadPoolSize(3)//推荐配置1-5
//				.discCacheFileNameGenerator(new Md5FileNameGenerator())
//				.tasksProcessingOrder(QueueProcessingType.LIFO)
//				.writeDebugLogs() // Remove for release app
//				.build();
//		// Initialize ImageLoader with configuration.
    	
    	File cacheDir = StorageUtils.getOwnCacheDirectory(context, "imageloader/Cache"); //缓存文件的存放地址
    	ImageLoaderConfiguration config = new ImageLoaderConfiguration 
    	.Builder(context) 
    	.memoryCacheExtraOptions(480, 800) // max width, max height 
    	.threadPoolSize(3)//线程池内加载的数量 
    	.threadPriority(Thread.NORM_PRIORITY - 2)  //降低线程的优先级保证主UI线程不受太大影响
    	.denyCacheImageMultipleSizesInMemory() 
    	.memoryCache(new LruMemoryCache(5 * 1024 * 1024)) //建议内存设在5-10M,可以有比较好的表现
    	.memoryCacheSize(5 * 1024 * 1024) 
    	.discCacheSize(50 * 1024 * 1024) 
    	.discCacheFileNameGenerator(new Md5FileNameGenerator()) 
    	.tasksProcessingOrder(QueueProcessingType.LIFO) 
    	.discCacheFileCount(100) //缓存的文件数量 
    	.discCache(new UnlimitedDiskCache(cacheDir)) 
    	.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) 
    	.imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)
    	.writeDebugLogs() // Remove for release app 
    	.build();
		ImageLoader.getInstance().init(config);
		
		

	      
	    options = new DisplayImageOptions.Builder()  
	     .showImageOnLoading(R.drawable.empty_photo4) //设置图片在下载期间显示的图片  
	     .showImageForEmptyUri(R.drawable.empty_photo4)//设置图片Uri为空或是错误的时候显示的图片  
	    .showImageOnFail(R.drawable.empty_photo4)  //设置图片加载/解码过程中错误时候显示的图片
	    .cacheInMemory(true)//设置下载的图片是否缓存在内存中  
//	    .memoryCache(new WeakMemoryCache())
	    .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中  
	    .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
//	    .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示  
	    .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示 
	    .bitmapConfig(android.graphics.Bitmap.Config.RGB_565)//设置图片的解码类型//  
//	    .decodingOptions(android.graphics.BitmapFactory.Options.class)//设置图片的解码配置  
	    //.delayBeforeLoading(int delayInMillis)//int delayInMillis为你设置的下载前的延迟时间
	    .delayBeforeLoading(0)//int delayInMillis为你设置的下载前的延迟时间
	    //设置图片加入缓存前，对bitmap进行设置  
	    //.preProcessor(BitmapProcessor preProcessor)  
	    .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位  
//	    .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少  ；避免使用他会创建新的ARGB_8888格式的Bitmap对象，OOM
	    .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间  
	    .build();//构建完成  

    }
    
    public DisplayImageOptions options;  
    
    
    
    public DisplayImageOptions getWholeOptions() {
        DisplayImageOptions options = new DisplayImageOptions.Builder()  
        .showImageOnLoading(R.drawable.empty_photo4) //设置图片在下载期间显示的图片  
        .showImageForEmptyUri(R.drawable.empty_photo4)//设置图片Uri为空或是错误的时候显示的图片  
        .showImageOnFail(R.drawable.empty_photo4)  //设置图片加载/解码过程中错误时候显示的图片
        .cacheInMemory(true)//设置下载的图片是否缓存在内存中  
        .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中  
        .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
        .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示  
        .bitmapConfig(android.graphics.Bitmap.Config.RGB_565)//设置图片的解码类型
        //.decodingOptions(BitmapFactory.Options decodingOptions)//设置图片的解码配置  
        .delayBeforeLoading(0)//int delayInMillis为你设置的下载前的延迟时间
        //设置图片加入缓存前，对bitmap进行设置  
        //.preProcessor(BitmapProcessor preProcessor)  
        .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位  
//        .displayer(new RoundedBitmapDisplayer(20))//不推荐用！！！！是否设置为圆角，弧度为多少  
        .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间，可能会出现闪动
        .build();//构建完成
        
        return options;
    }
    
	/**
	 * 实现定位回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			//Receive Location 
			if(location==null)
				return;
			if(location!=null
					&&location.getLongitude()!=0.0
					&& location.getLatitude()!=0.0
					&& location.getAddrStr()!=null){
			mLongitude = location.getLongitude();
			mLatitude = location.getLatitude();
			mGpsAddr = location.getAddrStr();
			Log.e("※※※※※※20140725地理位置※※※※※※", "※※※※※※经度:" + mLongitude + ",纬度:" + mLatitude + ",地址:" + mGpsAddr);
			
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());
			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");
			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());
			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation){
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\ndirection : ");
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				sb.append(location.getDirection());
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				//运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
			}
			Log.e("※※※※※※20140725BaiduLocationApiDem※※※※※※", sb.toString());
			}
			mLocationClient.stop();
			
		}
	}
	private void InitLocation(){
		option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);//设置定位模式Hight_Accuracy,Battery_Saving,Device_Sensors
		option.setOpenGps(true);
		
		option.setCoorType("bd09ll");//返回的定位结果是百度经纬度，默认值gcj02,bd09ll,bd09
		option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);//返回的定位结果包含地址信息
		mLocationClient.setLocOption(option);
	}
}
